package com.yuanchu.media.upload;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.MinioException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-01-26 11:18
 */
public class FileUploader {

    public static void main(String[] args)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            // 创建MinIO客户端，连接参数就是上述表格中的三个参数，127.0.0.1:9000、minioadmin、minioadmin
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint("192.168.101.130:9000")
                            .credentials("minioadmin", "minioadmin")
                            .build();

            // Make 'asiatrip' bucket if not exist.
            // 如果不存在，请制作 “asiatrips” 桶。
            // 由于backet我们已经手动创建了，所以这段代码可以删掉
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket("asiatrip").build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                // 制作一个名为 “asiatrips” 的新桶。
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
            } else {
                System.out.println("Bucket 'asiatrip' already exists.");
            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            // 将 '/home/user/Photos/asiaphotos.zip' 文件命名为 'asiaphotos-2015.zip'
            // 并上传到 'asiatrip' 里（示例代码创建的bucket）
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket("asiatrip")
                            .object("asiaphotos-2015.zip")
                            .filename("/home/user/Photos/asiaphotos.zip")
                            .build());
            // 这段输出也没有用，可以直接删掉
            // “Homeuserphotosasiaphotos.zip” 已作为 “对象 'asiaphotos-2015.zip” 成功上载到存储桶 “asiatrip'”。
            System.out.println(
                    "'/home/user/Photos/asiaphotos.zip' is successfully uploaded as "
                            + "object 'asiaphotos-2015.zip' to bucket 'asiatrip'.");
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
    }
}
